<?php

namespace App\Api;

use App\Http\Controllers\Controller;
use Auth;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class LoginController extends Controller
{

    //后台登录
    public function login(Request $request)
    {
        $request->validate([
            'mobile' => ['required', Rule::exists('users', 'mobile')],
            'password' => ['required'],
            'captcha.content' => ['required', 'captcha_api:'.request('captcha.key').',flat']
        ], [
            'account' => '帐号不能为空',
            'account.exists' => '帐号不存在',
            'password.required' => '密码不能为空',
            'captcha.content.required' => '验证码不能为空',
            'captcha.content.captcha_api' => '验证码输入错误'
        ]);
        $isLogin = Auth::attempt([
            'mobile' => $request->mobile,
            'password' => $request->password,
        ]);

        if ($isLogin) {
            $token = Auth::user()->createToken('token-name');
            return ['message' => '登录成功', 'token' => $token->plainTextToken];
        }
        return $this->error('账号或者密码错误');
    }

    //客户端登录
    public function clientLogin(Request $request)
    {
        $request->validate([
            'mobile' => ['required', Rule::exists('users', 'mobile')],
            'password' => ['required'],
        ], [
            'mobile.required' => '手机号不能为空',
            'mobile.exists' => '手机号不存在',
            'password.required' => '密码不能为空',
        ]);


        $isLogin = Auth::attempt([
            'mobile' => $request->mobile,
            'password' => $request->password,
        ]);
        if ($isLogin) {
            $token = Auth::user()->createToken('token-name');
            return ['message' => '登录成功', 'token' => $token->plainTextToken];
        }
        return $this->error('账号或者密码错误');
    }

    public function clientLogout()
    {
        Auth::logout();
        return $this->message('退出成功');
    }

    public function logout()
    {
        Auth::logout();
        return $this->message('退出成功');
    }
}
